package ltd.sshine.networkserver.handler;

import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelId;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.http.FullHttpRequest;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import ltd.sshine.networkcommon.constraint.ChannelConstraint;
import ltd.sshine.networkserver.holder.ServerConnectHolder;

@Slf4j
@ChannelHandler.Sharable
public class HttpProxyChannelHandler extends ChannelInboundHandlerAdapter {

    @Setter
    private ChannelHandlerContext clientCtx;


    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        FullHttpRequest fullHttpRequest = (FullHttpRequest) msg;
        //转发给客户端
        log.debug("转发请求给客户端");
        FullHttpRequest copy = fullHttpRequest.copy();
        ChannelId id = ctx.channel().id();
        copy.headers().add(ChannelConstraint.CHANNEL_ID, id.asLongText());
        ServerConnectHolder.addChannel(id.asLongText(), ctx.channel());
        clientCtx.writeAndFlush(copy);
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        ServerConnectHolder.removeChannel(ctx.channel().id().asLongText());
        super.channelInactive(ctx);
    }
}
